
import 'data_storer.dart';

mixin StorableMixin {
  DataStorer? _dataStorer;
  late Object _storeKey;

  DataStorer? get dataStorer => _dataStorer;

  set dataStorer(DataStorer? dataStorer) {
    if (_dataStorer == dataStorer) return;
    _dataStorer = dataStorer;
    getFromDataStorer();
  }

  Object get storeKey => _storeKey;
  set storeKey(Object storeKey) => _storeKey = storeKey;

  void getFromDataStorer();
  Future<void> putToDataStorer();
  Future<void> delete();
}

class StorableData<T> with StorableMixin {
  StorableData({
    required T initValue,
    required Object storeKey,
    bool? autoSave,
  }) : _value = initValue {
    _storeKey = storeKey;
  }

  T _value;
  T get value => _value;
  set value(T newValue) {
    if (_value != newValue) {
      _value = newValue;
      putToDataStorer();
    }
  }

  @override
  void getFromDataStorer() {
    _value = _dataStorer?.get(_storeKey) ?? _value;
  }

  @override
  Future<void> putToDataStorer() async {
    _dataStorer?.put(_storeKey, _value);
  }

  @override
  Future<void> delete() async {
    _dataStorer?.delete(_storeKey);
  }

  @override
  String toString() => _value.toString();
}
